package com.chart.web.controller.monitor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.chart.chart.domian.ChartConfigsUser;
import com.chart.chart.domian.ChartStatistics;
import com.chart.chart.domian.req.PUReq;
import com.chart.chart.domian.req.UListReq;
import com.chart.chart.domian.req.UVipsReq;
import com.chart.chart.domian.resp.PageResp;
import com.chart.chart.domian.resp.UserResp;
import com.chart.chart.domian.vo.ChartConfigsUserVo;
import com.chart.chart.domian.vo.PUVo;
import com.chart.chart.domian.vo.StatisticsVo;
import com.chart.chart.manager.UserStatisticsManager;
import com.chart.chart.service.IChartConfigsUserService;
import com.chart.chart.service.IChartStatisticsService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.common.core.domain.entity.UserCoinLog;
import com.chart.common.utils.poi.ExcelUtil;
import com.chart.system.domain.RegistrationChannels;
import com.chart.system.domain.SysUserOrder;
import com.chart.system.domain.vo.SysUserVo;
import com.chart.system.service.ISysUserOrderService;
import com.chart.system.service.ISysUserService;
import com.chart.system.service.IUserCoinLogsService;
import com.chart.system.service.RegistrationChannelsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台数据统计
 *
 * @author chart
 */
@Api(tags = "后台数据统计模块")
@RestController
@RequestMapping("/statistics")
public class StatisticsController extends BaseController {


    @Resource
    private UserStatisticsManager userManager;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    RegistrationChannelsService registrationChannelsService;

    @Autowired
    private IChartStatisticsService chartStatisticsService;

    @Autowired
    private IChartConfigsUserService chartConfigsUserService;


    /**
     * 后台统计分页查询
     * Luojiquan
     *
     * @param req
     * @return
     */
    //@PostMapping("/list")
    public AjaxResult getListBy(@RequestBody UListReq req) {
        List<UserResp> list = userManager.getListBy(req);
        for (UserResp userResp : list) {
            if (userResp.getHasPaid() != null) {
                if (userResp.getHasPaid() == 0) {
                    userResp.setHasPaidInfo("否");
                } else if (userResp.getHasPaid() == 1) {
                    userResp.setHasPaidInfo("是");
                }
            }

            //如果注册的时候未选择性别 默认值为3
            if (userResp.getSex() == "3") {
                userResp.setSex("null");
            }
            // 处理 hasCompleteInfo 字段
            if (userResp.getHasComplete() != null) {
                switch (userResp.getHasComplete()) {
                    case 0:
                        userResp.setHasCompleteInfo("未完善");
                        break;
                    case 1:
                        userResp.setHasCompleteInfo("已完善");
                        break;
                }
            }
            // 处理 platform 字段
            if (userResp.getPlatform() != null) {
                switch (userResp.getPlatform()) {
                    case 0:
                        userResp.setPlatformSecond("手机注册");
                        break;
                    case 1:
                        userResp.setPlatformSecond("电脑注册");
                        break;
                    default:
                        userResp.setPlatformSecond("未知平台");
                        break;
                }
            }
        }
        // 处理 knowChannel 字段
        for (UserResp userResp : list) {
            String knowChannelStr = userResp.getKnowChannel(); // 从 userResp 获取 knowChannel
            if (knowChannelStr != null) {
                try {
                    long knowChannel = Long.parseLong(knowChannelStr); // 将字符串转换为 long
                    if (knowChannel == 8) { // 如果 knowChannel 等于 8
                        String otherKnowChannel = userResp.getOtherKnowChannel();
                        if (otherKnowChannel != null) {
                            userResp.setKnowChannelSecond(otherKnowChannel); // 设置 knowChannelSecond 为 otherKnowChannel 的值
                        }
                    } else { // 如果 knowChannel 不等于 8
                        LambdaQueryWrapper<RegistrationChannels> lqw = new LambdaQueryWrapper<>();
                        lqw.eq(RegistrationChannels::getId, knowChannel);
                        // 查询对应的 RegistrationChannels
                        RegistrationChannels one = registrationChannelsService.getOne(lqw);
                        if (one != null) {
                            String name = one.getName();
                            userResp.setKnowChannelSecond(name); // 设置 knowChannelSecond
                        }
                    }
                } catch (NumberFormatException e) {
                    // 处理转换异常，例如记录日志或设置默认值
                    e.printStackTrace();
                }
            }
        }
        List<UserResp> lists = userManager.getListBy(req);

        PageResp<UserResp> resp = new PageResp();
        resp.setList(list);
        resp.setTotal((long) list.size());
        resp.setTotalUser(lists.size());
        return AjaxResult.success(resp);
    }






    @PostMapping("/list")
    public AjaxResult getListBys(@RequestBody UListReq req) {
        // 设置默认 pageSize
        if (req.getPageSize() == null) {
            req.setPageSize(10);
        }
        // 设置默认 pageNum
        if (req.getPageNum() == null) {
            req.setPageNum(1);
        }
        // 计算 offset
        // 假设 pageNum 从 1 开始
        int offset = (req.getPageNum() - 1) * req.getPageSize();
        req.setOffset(offset);
        PageResp<UserResp> pageResp = userManager.getListBys(req);
        return AjaxResult.success(pageResp);
    }





















    /**
     * 查询用户保存到我的生成的数量
     * @param req
     * @return
     */
    @PostMapping("query/chartConfigCount")
    public AjaxResult querychartConfigCount(@RequestBody UListReq req) {
        List<ChartConfigsUserVo> chartConfigsUsers = chartConfigsUserService.querychartConfigCount(req);

        return AjaxResult.success(chartConfigsUsers);
    }




    @ApiOperation("导出图表配置计数")
    @PostMapping("/export/chartConfigCountExport")
    public void chartConfigCountExport(HttpServletResponse response, @RequestBody UListReq req) {
        List<ChartConfigsUserVo> chartConfigsUsers = chartConfigsUserService.querychartConfigCount(req);
        ExcelUtil<ChartConfigsUserVo> util = new ExcelUtil<>(ChartConfigsUserVo.class);
        util.exportExcel(response, chartConfigsUsers, "用户保存管理");
    }




    /**
     * 根据用户id查询照片列表
     * @param
     * @return
     */


    @GetMapping("queryPhotosByUserId")
    public AjaxResult queryPhotosByUserId(Long userId) {

        List<ChartConfigsUser> list = chartConfigsUserService.queryPhotosByUserId(userId);
        return AjaxResult.success(list);
    }







   // @PostMapping("query/chartConfigCount")
    public AjaxResult querychartConfigCount2(@RequestBody UListReq req) {
        List<ChartConfigsUserVo> chartConfigsUsers = chartConfigsUserService.querychartConfigCount2(req);

        return AjaxResult.success(chartConfigsUsers);
    }



    @GetMapping("/getSource")
    public AjaxResult getSource() {
        return userManager.getSource();
    }


    @ApiOperation("导出用户数")
    @PostMapping("/exportUser")
    public void export(HttpServletResponse response, @RequestBody UListReq req) {
        List<UserResp> list = userManager.getListBy(req);
        ExcelUtil<UserResp> util = new ExcelUtil<UserResp>(UserResp.class);
        util.exportExcel(response, list, "用户数据");
    }

    @ApiOperation("获取用户PV、UV操作记录")
    @PostMapping("/getPU")
    public AjaxResult getPU(@RequestBody PUReq req) {
        List<PUVo> list = userManager.getPU(req);
        return AjaxResult.success(list);
    }


    @ApiOperation("导出用户PV、UV操作记录")
    @PostMapping("/exportPU")
    public void OpersExport(HttpServletResponse response, @RequestBody PUReq req) {
        List<PUVo> list = userManager.getPU(req);
        ExcelUtil<PUVo> util = new ExcelUtil<PUVo>(PUVo.class);
        util.exportExcel(response, list, "操作数据");
    }

    @ApiOperation("修改用户Vip信息")
    @PostMapping("/addVips")
    public AjaxResult editVips(@RequestBody UVipsReq req) {
        return userManager.editVips(req);
    }


    @ApiOperation("刷新会员信息")
    @GetMapping("/updateVips")
    public AjaxResult updateVips() {
        return userManager.updateVips();
    }


    /**
     * 使用说明点击的操作记录每次点击数据加1
     *
     * @return
     */
    @PostMapping("/operationPv")
    public AjaxResult operationPv() {
        return chartStatisticsService.operationPv();
    }


    //使用说明点击的操作记录查询
    @GetMapping("/operationTotal")
    public AjaxResult operationTotal() {
        return chartStatisticsService.operationTotal();
    }


    @Autowired
    private IUserCoinLogsService userCoinLogsService;

    /**
     * 总登录次数、月登录次数、
     * 付费用户标识（包括vip/智点购买）
     *
     * @return
     */
    @GetMapping("demo")
    public AjaxResult query() {
        List<UserResp> list = userCoinLogsService.querydemo();
        if (list == null) {
            throw new RuntimeException("查询结果为空");
        }
        return AjaxResult.success(list);
    }


}
